package com.example.forum.service.impl;

import com.example.forum.dao.MessageDao;
import com.example.forum.domain.Message;
import com.example.forum.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageDao messageDao;

    @Override
    public Map<String,List<Message>> findByFromToId(int fromToId) {
        Map<String,List<Message>> map=new TreeMap<>();
        //查询出这个用户所有的消息
        List<Message> messages = messageDao.findByFromToId(fromToId);
        //将所有的信息按照conversationId分组
        for(Message message:messages){
            if(map.get(message.getConversationId())==null){
                List<Message> list=new ArrayList<>();
                list.add(message);
                map.put(message.getConversationId(),list);
            }else {
                map.get(message.getConversationId()).add(message);
            }
        }
        return map;
    }

    @Override
    public int findCount(int id1, int id2) {
        if(id1<id2){
            return messageDao.findCount(id1+"_"+id2);
        }
        return messageDao.findCount(id2+"_"+id1);
    }

    @Override
    public int findUnreadCount(int fromId, int toId) {
        return messageDao.findUnreadCount(fromId,toId);
    }

    //id1代表当前登录的用户，id2代表与当前用户对话的用户
    @Override
    public List<Message> findAllSession(int id1,int id2) {
        if(id1<id2){
            return messageDao.findAllSession(id1+"_"+id2);
        }
        return messageDao.findAllSession(id2+"_"+id1);
    }

    @Override
    public int totalUnreadCount(int toId) {
        return messageDao.totalUnreadCount(toId);
    }

}
